﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace IGolovkine.Core
{
    public static class MethodHelper
    {
        public static TResult InvokeWithTimeout<TParam, TResult>(TimeSpan timeout, TParam param, Func<TParam, TResult> func)
        {
            Thread subThread = null;

            Func<TParam, TResult> wrappedFunc = p =>
            {
                subThread = Thread.CurrentThread;
                return func(p);
            };

            IAsyncResult result = wrappedFunc.BeginInvoke(param, null, null);
            if (((timeout != TimeSpan.Zero) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
            {
                if (subThread != null)
                {
                    subThread.Abort();
                }
                throw new TimeoutException();
            }
            else
            {
                return wrappedFunc.EndInvoke(result);
            }
        }

        public static TResult InvokeWithTimeout<TResult>(TimeSpan timeout, Func<TResult> func)
        {
            return InvokeWithTimeout(timeout, 0, p => func());
        }

        public static void InvokeWithTimeout(TimeSpan timeout, Action action)
        {
            InvokeWithTimeout<int, int>(timeout, 0, (p) => { action(); return -1; });
        }

        public static void InvokeAsynchronously(Action action)
        {
            InvokeAsynchronously(action, null);
        }

        public static void InvokeAsynchronously(Action action, Action<Exception> exceptionCallBack)
        {
                action.BeginInvoke(new AsyncCallback(r => 
                {
                    try
                    {
                        action.EndInvoke(r);
                    }
                    catch (Exception ex)
                    {
                        if (exceptionCallBack != null)
                        {
                            exceptionCallBack(ex);
                        }
                    }
                }), null);
            
        }
    }
}
